package com.party.admin.biz.mall;

import com.google.common.base.Function;
import com.party.admin.biz.distribution.DistributionBizService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.input.common.CommonQuery;
import com.party.admin.web.dto.output.mall.MallShowSubjectOutput;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.mall.*;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.mall.*;
import com.party.core.service.mall.biz.GoodsShowCountBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * 展示商品主题
 * Created by wei.li
 *
 * @date 2017/8/25 0025
 * @time 16:21
 */

@Service
public class MallShowSubjectBizService {

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private IMallShowSubjectService mallShowSubjectService;

    @Autowired
    private IMallShowSubjectTemplateService mallShowSubjectTemplateService;

    @Autowired
    private IMallShowCategoryService mallShowCategoryService;

    @Autowired
    private IMallShowGoodsService mallShowGoodsService;

    @Autowired
    private DistributionBizService distributionBizService;

    @Autowired
    private MallShowCategoryBizService mallShowCategoryBizService;

    @Autowired
    private GoodsShowCountBizService goodsShowCountBizService;

    @Autowired
    private IMallStoreResourcesService mallStoreResourcesService;

    public static final String SHOW_SUBJECT_FOLDER = "showSubject";

    public static final String SHOW_SUBJECT_FOLDER_NEW = "showSubject_new";

    private static final String CODE_PATH = "/mallShowSubject/";


    private static final String url = "/mall/mall_show_goods.html?id=";

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 展示商品主题列表
     *
     * @param mallShowSubjectQuery 主题
     * @param page                 分页参数
     * @return 列表数据
     */
    public List<MallShowSubjectOutput> list(MallShowSubjectQuery mallShowSubjectQuery, Page page) {

        if (null != mallShowSubjectQuery.getTimeType() && !new Integer(0).equals(mallShowSubjectQuery.getTimeType())) {
            CommonQuery commonQuery = new CommonQuery();
            commonQuery.setTimeType(mallShowSubjectQuery.getTimeType());
            mallShowSubjectQuery.setCreateStart(commonQuery.getCreateStart());
            mallShowSubjectQuery.setCreateEnd(commonQuery.getCreateEnd());
        }

        List<MallShowSubjectWithAuthor> mallShowSubjectList = mallShowSubjectService.queryListPage(mallShowSubjectQuery, page);
        return LangUtils.transform(mallShowSubjectList, new Function<MallShowSubjectWithAuthor, MallShowSubjectOutput>() {
            @Override
            public MallShowSubjectOutput apply(MallShowSubjectWithAuthor mallShowSubject) {
                String filePath = fileBizService.getUploadCIPath(mallShowSubject.getCreateBy(), SHOW_SUBJECT_FOLDER_NEW);
                MallShowSubjectOutput mallShowSubjectOutput = MallShowSubjectOutput.transform(mallShowSubject);
                String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + mallShowSubject.getId());
                mallShowSubjectOutput.setQrCode(qrCodeUrl);
                return mallShowSubjectOutput;
            }
        });
    }

    /**
     * 删除主题
     *
     * @param subjectId 主题id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean deleteSubjectBiz(String subjectId) {
        boolean endResult = true;
        String memberId = null;
        try {
            if (StringUtils.isEmpty(subjectId)) {
                endResult = false;
                return endResult;
            }
            MallShowSubject subject = mallShowSubjectService.get(subjectId);
            if (subject == null) {
                endResult = false;
                return endResult;
            }
            memberId = subject.getMemberId();
            mallShowCategoryService.deleteBySubjectId(subjectId);
            mallShowSubjectService.delete(subjectId);
            List<MallShowSubject> mallShowSubjects = mallShowSubjectService.findByMemberId(memberId);
            if (mallShowSubjects.size() == 0) {
                List<MallShowGoods> mallShowGoods = mallShowGoodsService.findBySubjectId(subjectId);
                for (MallShowGoods showGoods : mallShowGoods) {
                    distributionBizService.deleteDistributionBiz(showGoods.getTargetId(), memberId);
                }
            }
            mallStoreResourcesService.deleteByTargetId(subjectId);
            mallShowGoodsService.deleteBySubjectId(subjectId);
        } catch (Exception e) {
            endResult = false;
            logger.error("删除主题失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            if (endResult) {
                try {
                    String filePath = fileBizService.getUploadCIPath(memberId, SHOW_SUBJECT_FOLDER_NEW);
                    String detailPath = CosBizService.getDeleteQrCodePath(filePath, subjectId);
                    cosBizService.deleteFile(detailPath);
                } catch (Exception e) {
                    logger.error("删除主题二维码失败", e);
                }
            }
        }
        return endResult;
    }

    /**
     * 保存主题
     *
     * @param mallShowSubject 主题
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean saveSubjectBiz(MallShowSubject mallShowSubject) {
        try {
            MemberGroup member = RealmUtils.getCurrentUser();
            //处理富文本
            if (StringUtils.isNotEmpty(mallShowSubject.getContent())) {
                String content = StringUtils.escapeHtml4Iframe2Video(mallShowSubject.getContent().trim());
                mallShowSubject.setContent(content);
            }
            if (StringUtils.isNotEmpty(mallShowSubject.getBuyInstruction())) {
                String buyInstruction = StringUtils.escapeHtml4Iframe2Video(mallShowSubject.getBuyInstruction().trim());
                mallShowSubject.setBuyInstruction(buyInstruction);
            }

            if (StringUtils.isEmpty(mallShowSubject.getId())) {
                // 统计模板的机构量
                try {
                    goodsShowCountBizService.addOrgNum(mallShowSubject.getTemplateId(), mallShowSubject.getMemberId(), true);
                } catch (Exception e) {
                    logger.error("添加机构主题时, 统计模板的机构数量异常", e);
                }

                if (StringUtils.isNotEmpty(mallShowSubject.getTemplateId())) {
                    MallShowSubjectTemplate mallShowSubjectTemplate = mallShowSubjectTemplateService.get(mallShowSubject.getTemplateId());
                    mallShowSubject.setGoodsNum(mallShowSubjectTemplate.getGoodsNum());
                }
                mallShowSubject.setCreateBy(member.getId());
                mallShowSubject.setUpdateBy(member.getId());
                String subjectId = mallShowSubjectService.insert(mallShowSubject);

                if (StringUtils.isNotEmpty(mallShowSubject.getTemplateId())) {
                    // 复制模板的商品到机构商品中去
                    try {
                        mallShowCategoryBizService.copyCategoryBiz(mallShowSubject.getTemplateId(), subjectId, true, mallShowSubject.getMemberId());
                    } catch (Exception e) {
                        logger.error("添加机构主题复制商品时异常", e);
                    }
                }
            } else {
                MallShowSubject db = mallShowSubjectService.get(mallShowSubject.getId());

                mallShowSubject.setCreateBy(db.getCreateBy());
                mallShowSubject.setUpdateBy(member.getId());
                mallShowSubjectService.update(mallShowSubject);

                // 统计模板的机构量
                try {
                    MallShowSubject oldSubject = mallShowSubjectService.get(mallShowSubject.getId());
                    goodsShowCountBizService.updateOrgNum(oldSubject.getMemberId(), mallShowSubject.getMemberId(), mallShowSubject.getTemplateId());
                } catch (Exception e) {
                    logger.error("更新机构主题时, 统计模板的机构数量异常", e);
                }

            }
            return true;
        } catch (Exception e) {
            logger.error("保存主题失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }

    /**
     * 复制主题
     *
     * @param subjectId 主题id
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public MallShowSubject copySubjectBiz(String subjectId) {
        MemberGroup cur = RealmUtils.getCurrentUser();
        /*1.修改主题对象*/
        MallShowSubject mallShowSubject = mallShowSubjectService.get(subjectId);
        mallShowSubject.setId(null);
        mallShowSubject.setCreateDate(null);
        mallShowSubject.setUpdateDate(null);
        mallShowSubject.setCreateBy(cur.getId());
        mallShowSubject.setUpdateBy(cur.getId());
        mallShowSubjectService.insert(mallShowSubject);
        /*修改展示商品类型*/
        mallShowCategoryBizService.copyCategoryBiz(subjectId, mallShowSubject.getId(), false, mallShowSubject.getMemberId());
        return mallShowSubject;
    }
}
